<template>
  <AdminLayout>
    <el-card class="add-student-card">
      <template #header>
        <div class="card-header">
          <h2>添加学生</h2>
        </div>
      </template>
      
      <el-form :model="studentForm" :rules="rules" ref="studentFormRef" label-width="120px"
                :disabled="submitting"
                class="student-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="studentForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="studentForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="studentForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="studentForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="studentForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="未知">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="studentForm.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select
            v-model="studentForm.classId"
            placeholder="请选择班级"
            filterable
            :filter-method="(query: string) => { classSearchQuery = query }"
            remote
            :remote-method="(query: string) => { classSearchQuery = query }"
            :loading="false"
          >
            <el-option
              v-for="cls in classList"
              :key="String(cls.value)"
              :label="cls.label"
              :value="cls.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollmentDate">
          <el-date-picker v-model="studentForm.enrollmentDate" type="date" placeholder="选择入学日期" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postJson } from '../../utils/api'
import AdminLayout from '../../components/admin/AdminLayout.vue'

// 定义类型接口
interface ClassItem {
  value: string | number;
  label: string;
}

const router = useRouter()

// 表单引用
const studentFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const studentForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: '未知',
  studentNo: '',
  classId: '',
  enrollmentDate: '',
  phone: '',
  email: ''
})

// 提交状态
const submitting = ref(false)

// 班级列表数据
const classList = ref<ClassItem[]>([])

// 班级搜索关键字
const classSearchQuery = ref<string>('')

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== studentForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  studentNo: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^S\d{6}$/, message: '学号格式应为 S 加 6 位数字', trigger: 'blur' }
  ],
  classId: [
    { required: true, message: '请选择班级', trigger: 'change' }
  ],
  enrollmentDate: [
    { required: true, message: '请选择入学日期', trigger: 'change' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
})

// 提交表单
const handleSubmit = async () => {
  if (!studentFormRef.value) return
  
  try {
    // 表单验证
    await studentFormRef.value.validate()
    
    // 设置提交状态
    submitting.value = true
    
    // 准备请求数据 - 根据后端接口要求构建参数
    const submitData = {
      username: studentForm.username,
      password: studentForm.password,
      realName: studentForm.realName,
      gender: studentForm.gender,
      studentNo: studentForm.studentNo,
      classId: studentForm.classId,
      enrollmentDate: studentForm.enrollmentDate,
      phone: studentForm.phone || '',
      email: studentForm.email || '',
      roleId: 3 // 学生角色ID为3
    }
    
    // 调用后端API添加学生
    const result = await postJson('/student/add', submitData)
    
    // 根据API返回结果处理
    if (result.code === 200) {
      ElMessage.success(result.msg || '添加学生成功')
      // 返回学生列表页面
      router.push('/admin/student/list')
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    if (error !== false) { // 如果不是表单验证失败
      console.error('添加学生失败:', error)
      ElMessage.error('网络错误，请检查后端服务是否正常运行')
    }
  } finally {
    submitting.value = false
  }
}

// 加载班级列表
const loadClassList = async () => {
  try {
    // 使用相对路径发送请求，避免URL重复拼接
    const result = await get('/class/query')
    
    if (result.code === 200 && result.data) {
      // 处理班级数据，将显示文本格式化为 grade+major+className
      classList.value = result.data.map((cls: any) => ({
        value: cls.classId,
        label: `${cls.grade || ''}${cls.major || ''}${cls.className || ''}`
      }))
    } else {
      ElMessage.error('获取班级列表失败')
    }
  } catch (error) {
    console.error('加载班级列表失败:', error)
    ElMessage.error('网络错误，请检查后端服务')
  }
}

// 取消操作
const handleCancel = () => {
  // 返回学生列表页面
  router.push('/admin/student/list')
}

// 页面加载时获取班级数据
onMounted(() => {
  loadClassList()
})
</script>

<style scoped>
/* 重置样式并确保容器填满整个屏幕 */
:deep(.el-card) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  border-radius: 0;
  border: none;
}

/* 外层容器完全填充满屏幕 */
.add-student-container {
  padding: 0 !important;
  min-height: 100vh;
  height: 100vh;
  background-color: #fff;
  width: 100vw !important;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  overflow: hidden;
}

/* 卡片样式 */
.add-student-card {
  max-width: 600px;
  margin: 0 auto;
  width: 100% !important;
  padding: 0 !important;
  border: none;
  background-color: #fff;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.card-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

/* 表单样式 */
.student-form {
  padding: 20px 0;
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  background-color: #fff;
  flex: 1;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-form-item__content) {
  width: 100%;
}

/* 输入框和选择框样式 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-date-editor) {
  width: 100%;
  max-width: 500px;
}

/* 按钮区域样式 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-header {
    padding: 15px;
  }
  
  .student-form {
    padding: 15px;
  }
  
  :deep(.el-input__wrapper),
  :deep(.el-select__wrapper),
  :deep(.el-date-editor) {
    width: 100%;
    max-width: none;
  }
  
  .form-actions {
    justify-content: center;
  }
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
}
</style>